package com.zshy.base.tob.satoken.factory;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * YAML 配置源工厂
 *
 * @author zhouhengzhe
 */
public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {

    /**
     * 创建配置源
     *
     * @param name
     * @param resource
     * @return
     * @throws IOException
     */
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = resource.getResource().getFilename();
        if (StringUtils.hasText(sourceName) &&
                (StringUtils.endsWithIgnoreCase(sourceName, ".yaml") || StringUtils.endsWithIgnoreCase(sourceName, ".yml"))) {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return new PropertiesPropertySource(sourceName, Objects.requireNonNull(factory.getObject()));
        }
        return super.createPropertySource(name, resource);
    }

}
